package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述
 *
 * @author ZhangKai
 * @version 1.0
 * @createDate 2025/2/27 9:35
 **/
@Component
public class WriteLB implements LoadBalancer{

    @Override
    public ServiceInstance getInstance(List<ServiceInstance> serviceInstances) {
        //获取本次请求的下标
        int index = getIndex() % serviceInstances.size();
        //本次请求节点
        return serviceInstances.get(index);
    }

    private final AtomicInteger atomicInteger = new AtomicInteger(0);
    private int getIndex() {
        int current;
        int next;
        do
        {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while(!this.atomicInteger.compareAndSet(current, next));
        System.out.println("*****next: "+next);
        return next;
    }
}
